//
//  WSSearchViewController.m
//  GroupFourFM
//
//  Created by dllo on 15/12/29.
//  Copyright © 2015年 GroupFour. All rights reserved.
//

#import "WSSearchViewController.h"
#import "WSResource.h"
#import "WSSearchModel.h"
#import "WSTrackModel.h"
#import "WSAlbumsDetailViewController.h"
#import "WSAlbumDetailTableViewCell.h"
#import "WHCategoryTableViewCell.h"
#import "WSPlayViewController.h"
#import "WSAlbumsDetailViewController.h"

@interface WSSearchViewController ()<UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *myArray;

@property (nonatomic, strong) NSMutableArray *albumArray;

@property (nonatomic, strong) NSMutableArray *trackArray;

@property (nonatomic, assign) NSInteger num;

@property (nonatomic, assign) BOOL isSearch;

@property (nonatomic, strong) UISearchBar *searchBar;

@end

@implementation WSSearchViewController

- (void)viewWillAppear:(BOOL)animated {

    self.navigationController.navigationBarHidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {

    self.navigationController.navigationBarHidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self createSubView];
}

- (void)createSubView {
    
    _isSearch = NO;
    
    UIView *view = [[UIView alloc] init];
    [self.view addSubview:view];
    view.backgroundColor = [UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.left.right.mas_equalTo(@0);
        make.height.mas_equalTo(@64);
    }];
    
    self.searchBar = [[UISearchBar alloc] init];
    [view addSubview:self.searchBar];
    self.searchBar.backgroundColor = [UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1];
    self.searchBar.searchBarStyle = UISearchBarStyleMinimal;
    self.searchBar.delegate = self;
    self.searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
    self.searchBar.autocapitalizationType = UITextAutocapitalizationTypeNone;
    self.searchBar.placeholder = @"Search";
    self.searchBar.keyboardType =  UIKeyboardTypeDefault;
    self.searchBar.layer.borderWidth = 0;
    [self.searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.mas_equalTo(UIEdgeInsetsMake(24, 0, 10, 0));
    }];
    [self.searchBar becomeFirstResponder];

    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.sectionFooterHeight = 0.1;
    [self.view addSubview:_tableView];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.tableView registerClass:[WSAlbumDetailTableViewCell class] forCellReuseIdentifier:@"albumCell"];
    [self.tableView registerClass:[WHCategoryTableViewCell class] forCellReuseIdentifier:@"categoryCell"];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(view.mas_bottom);
        make.left.right.bottom.mas_equalTo(@0);
    }];
}

#pragma makr - searchBar delegate
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {

    searchBar.showsCancelButton = YES;
    for(UIView *view in  [[[searchBar subviews] objectAtIndex:0] subviews]) {
        if([view isKindOfClass:[NSClassFromString(@"UINavigationButton") class]]) {
            UIButton * cancel =(UIButton *)view;
            [cancel setTitle:@"取消" forState:UIControlStateNormal];
        }
    }
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {

    if ([searchText isEqualToString:@""]) {
        _myArray = [NSMutableArray array];
        _albumArray = [NSMutableArray array];
        _trackArray = [NSMutableArray array];
        _isSearch = NO;
        [self.tableView reloadData];
    }
    [self getData:searchText];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {

    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - tableView delegate && dataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    if (_isSearch) {
        return 2;
    }
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if (_isSearch) {
        if (section == 0) {
            return _albumArray.count;
        }
        else {
            return _trackArray.count;
        }
    }
    return _myArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (_isSearch) {
        if (indexPath.section == 0) {
            return SCREEN_WIDTH * 0.3;
        }
        return 120;
    }
    return 44;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {

    if (_isSearch) {
        return 40;
    }
    return 0.1;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {

    if (_isSearch) {
        if (section == 0) {
            return @"专辑";
        }
        return @"声音";
    }
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (_isSearch) {
        
        if (indexPath.section == 0) {
        
            WHCategoryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"categoryCell"];
            WSAlbumModel *albumModel = [_albumArray objectAtIndex:indexPath.row];
            albumModel.albumCoverUrl290 = albumModel.cover_path;
            cell.albumModel = albumModel;
            
            return cell;
        }
        else {
        
            WSAlbumDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"albumCell"];
            WSTrackModel *trackModel = [_trackArray objectAtIndex:indexPath.row];
            trackModel.coverSmall = trackModel.cover_path;
            cell.trackModel = trackModel;
            
            return cell;
        }
    }
    else {
    
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        
        WSSearchModel *model = [self.myArray objectAtIndex:indexPath.row];
        
        cell.textLabel.text = [model keyword];
        
        if (model.imgPath != nil) {
            [cell.imageView sd_setImageWithURL:[NSURL URLWithString:model.imgPath] placeholderImage:PLACEHOLDER_CELL_SAME];
        }
        
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    [_searchBar resignFirstResponder];
    if (_isSearch) {
        if (indexPath.section == 0) {
            WSAlbumsDetailViewController *albumDVC = [[WSAlbumsDetailViewController alloc] init];
            WSAlbumModel *album = _albumArray[indexPath.row];
            albumDVC.title = album.title;
            albumDVC.albumId = album.myId;
            [self.navigationController pushViewController:albumDVC animated:YES];
        } else {
            WSPlayViewController *playVC = [WSPlayViewController sharaMusicPlayer];
            UINavigationController *navC = [[UINavigationController alloc] initWithRootViewController:playVC];
            WSTrackModel *track = _trackArray[indexPath.row];
            playVC.song_id = track.trackId;
            playVC.allMusicArray = self.trackArray;
            playVC.indexRow = indexPath.row;
            [self presentViewController:navC animated:YES completion:nil];
        }
        
    }
    else {
        if (indexPath.row < _num) {
            
            WSAlbumsDetailViewController *albumsDVC = [[WSAlbumsDetailViewController alloc] init];
            
            WSSearchModel *albumModel = self.myArray[indexPath.row];
            albumsDVC.albumId = albumModel.myId;
            albumsDVC.title = albumModel.keyword;
            [self.navigationController pushViewController:albumsDVC animated:YES];
        }
        else {
        
            WSSearchModel *albumModel = self.myArray[indexPath.row];
            [self getMoreData:albumModel.keyword];
            _isSearch = YES;
        }
    }
}

#pragma mark - 请求数据
-(void)getData:(NSString *)searchString
{

    self.myArray = [NSMutableArray array];
    NSString *string = [NSString stringWithFormat:@"http://search.ximalaya.com/suggest?device=iphone&kw=%@", searchString];
    [WSResource getDataWithURL:string block:^(id result) {
        
        _num = [[result objectForKey:@"albumResultNum"] integerValue];
        NSMutableArray *albumArray = [result objectForKey:@"albumResultList"];
        for (NSMutableDictionary *albumDic in albumArray) {
            WSSearchModel *model = [WSSearchModel modelWithDictionary:albumDic];
            [self.myArray addObject:model];
        }
        
        NSMutableArray *queryArray = [result objectForKey:@"queryResultList"];
        for (NSMutableDictionary *queryDic in queryArray) {
            
            WSSearchModel *model = [WSSearchModel modelWithDictionary:queryDic];
            [self.myArray addObject:model];
        }
        
        
//        [GiFHUD dismiss];
        [self.tableView reloadData];
    } error:^(NSError *error) {
//        [GiFHUD dismiss];
        NSLog(@"数据请求失败 error");
    }];
}

#pragma mark - 请求点击cell搜索的数据
-(void)getMoreData:(NSString *)cellString
{
    //    [self createHud];
    NSString *str = [NSString stringWithFormat:@"http://search.ximalaya.com/front/v1?device=iphone&core=all&kw=%@&page=1&rows=3&spellchecker=true",cellString];
    
    [WSResource getDataWithURL:str block:^(id result) {
        self.albumArray = [NSMutableArray array];
        self.trackArray = [NSMutableArray array];
        NSMutableArray *albumArray = [[result objectForKey:@"album"] objectForKey:@"docs"];
        for (NSMutableDictionary *dic in albumArray) {
            WSAlbumModel *model = [WSAlbumModel modelWithDictionary:dic];
            [self.albumArray addObject:model];
        }
        
        NSMutableArray *trackArray = [[result objectForKey:@"track"] objectForKey:@"docs"];
        for (NSMutableDictionary *dic in trackArray) {
            WSTrackModel *model = [WSTrackModel modelWithDictionary:dic];
            [self.trackArray addObject:model];
        }

//        [GiFHUD dismiss];
        [self.tableView reloadData];
        
    } error:^(NSError *error) {
//        [GiFHUD dismiss];
        NSLog(@"%@", error);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
